package com.geor.gcv.core.process;

import java.util.ArrayList;
import java.util.List;

import org.nutz.log.Loggers;
import org.opencv.core.Mat;
import org.slf4j.Logger;

import com.geor.gcv.core.mat.Mats;
import com.geor.gcv.core.model.Area;

/**
 * 去除周围黑边
 * 
 * @author geor.lusongnan
 *
 */
public class ClearBlackProcess extends Process {
	private Process process;
	protected Logger log = Loggers.get();

	public ClearBlackProcess(Process process) {
		setProcess(process);
	}

	@Override
	public String getProcessName() {
		return process.getProcessName() + "-->去除周围黑色区域";
	}

	@Override
	public Mat process() {
		Mat mat = process.process();
		int start = 0;
		int end = mat.rows();

		List<Integer> lists = new ArrayList<Integer>();
		// 判断行是否为黑
		boolean flag = true;
		for (int row = 0; row < mat.rows(); row++) {
			int sum_white_pex = 0;
			for (int col = 0; col < mat.cols(); col++) {
				int pex = (int) mat.get(row, col)[0];
				if (pex == Mats.PEX_WHITE) {
					sum_white_pex++;
				}
				// 如果该行白点数量大于2 该行就不是背景
				if (sum_white_pex >= 2) {
					flag = false;
					break;
				}
			}
			if (!flag) {
				lists.add(row);
				flag = true;
			}
		}
		if (lists.size() == 0) {
			return deal(mat, 0, mat.rows() - 1);
		}

		start = lists.get(0);
		end = lists.get(lists.size() - 1);

		for (int i = 0; i < lists.size() - 1; i++) {
			int value1 = lists.get(i + 1);
			int value2 = lists.get(i);
			int poor = value1 - value2;
			// 满足记录该位置为干扰点
			if (poor >= 10) {
				start = value1;
			}
		}

		if (start >= end) {
			start = end - 1;
		}

		return deal(mat, start, end);
	}

	private Mat deal(Mat mat, int start, int end) {
		ScreenShootProcess process = new ScreenShootProcess(new InputProcess(mat),
				new Area(0, start, mat.cols(), end - start));
		return process.process();
	}

	public void setProcess(Process process) {
		this.process = process;
	}

}
